#pragma once
#include<iostream>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include <cstring>
#include<string>
#include <cstdlib>
#include"Log.hpp"

enum{
    SocketErr=2,
    BindErr,
    ListenErr,
};

const int backlog = 10; // 后面解释
class Sock
{
public:
    Sock()
    {}

    ~Sock()
    {}

    void Socket()
    {
        _sockfd=socket(AF_INET,SOCK_STREAM,0);
        if(_sockfd<0)
        {
            lg(Fatal,"socker error,%s:%d",strerror(errno),errno);
            exit(SocketErr);
        }
        int opt=1;
        setsockopt(_sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));//允许重复调用某个端口
    }

    void Bind(uint16_t port)
    {
        sockaddr_in local;
        local.sin_family=AF_INET;
        local.sin_port=htons(port);
        local.sin_addr.s_addr=INADDR_ANY;//让服务器监听主机上所有可用的网络接口(IP地址) internet address
        
        if(bind(_sockfd,(sockaddr*)&local,sizeof(local))<0)
        {
            lg(Fatal,"bind error,%s:%d",strerror(errno),errno);
            exit(BindErr);
        }
    }

   int Accept(std::string*clientip,uint16_t*clientport)
    {
        sockaddr_in peer;
        socklen_t len=sizeof(peer);
        int newfd=accept(_sockfd,(sockaddr*)&peer,&len);
        if(newfd<0)
        {
            lg(Warning,"accept error,%s:%d",strerror(errno),errno);
            return -1;
        }
        char ipstr[64];
        inet_ntop(AF_INET,&peer.sin_addr,ipstr,sizeof(ipstr));
        *clientip=ipstr;
        *clientport=ntohs(peer.sin_port);
        return newfd;
    }

    void Listen()
    {
        if(listen(_sockfd,backlog)<0)
        {
            lg(Fatal,"listen error,%s:%d",strerror(errno),errno);
            exit(ListenErr);
        }
    }

    bool Connect(const std::string &ip,uint16_t&port)
    {
        sockaddr_in peer;
        bzero(&peer,sizeof(peer));
        peer.sin_family=AF_INET;
        peer.sin_port=htons(port);
        inet_pton(AF_INET,ip.c_str(),&(peer.sin_addr));
        
        int n=connect(_sockfd,(sockaddr*)&peer,sizeof(peer));
        if(n==-1)
        {
            std::cerr<<"connect to "<<ip<<":"<<port<<"error"<<std::endl;
            return false;
        } 
        return 1;      
    }

    void Close()
    {
        close(_sockfd);
    }

    int getfd()
    {
        return _sockfd;
    }
private:
    int _sockfd;
};